{% extends "base.html" %}
{% load static %}

{% block title %}
{{ article.title }}
{% endblock title %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-9">
            <h1 class="mt-4 mb-4">{{ article.title }}</h1>
            <div class="alert alert-success">
                <div class="d-flex justify-content-between align-items-center">
                    <span>
                        {% if user.profile.avatar %}
                        <img src="{{ user.profile.avatar.url }}" class="rounded-circle mr-2"
                            style="width: 30px; height: 30px; object-fit: cover;">
                        {% else %}
                        <img src="{% static 'images/default_avatar.png' %}" class="rounded-circle mr-2"
                            style="width: 30px; height: 30px; object-fit: cover;">
                        {% endif %}
                        {{ article.author }}
                        {% if user == article.author %}
                        <span class="ml-2">
                            <a class="btn btn-sm btn-danger confirm-delete" href="#" onclick="confirm_safe_delete()">
                                <i class="fas fa-trash"></i> 删除
                            </a>
                            <a class="btn btn-sm btn-primary" href="{% url 'article:article_update' article.id %}">
                                <i class="fas fa-edit"></i> 编辑
                            </a>
                            
                        </span>
                        
                        {% endif %}
                    </span>
                    <!-- 新增点赞按钮 -->
<div style="text-align:center;" class="mt-4">
    <button class="btn btn-outline-danger"
            type="button"
            onclick="validate_is_like(
                     '{% url 'article:increase_likes' article.id %}',
                     {{ article.id }},
                     {{ article.likes }}
                     )"
            >
        <span>点赞</span>
        <span>
            <i class="fas fa-heart"></i>
        </span>
        <span id="likes_number">
            {{ article.likes }}
        </span>
    </button>
                    <span>
                        <i class="fas fa-eye"></i> {{ article.total_views }}
                    </span>
                </div>
            </div>
            
            <div class="article-body mt-4 mb-4">
                {{ article.body|safe }}
            </div>

            <div class="comment-area card mt-4">
                <div class="card-body">
                    {% if user.is_authenticated %}
                    <h4 class="card-title">发表评论</h4>
                    <!-- 添加加载状态显示 -->
                    <div id="comment-loading" class="comment-form-loading">
                        <div class="spinner-border text-primary" role="status">
                            <span class="sr-only">加载中...</span>
                        </div>
                    </div>
                    <form id="comment-form" class="comment-form-hidden"
                        action="{% url 'comment:post_comment' article.id %}" method="POST">
                        {% csrf_token %}
                        <div class="form-group">
                            <div>
                                {{ comment_form.media }}
                                {{ comment_form.body }}
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary mt-2">
                            <i class="fas fa-paper-plane"></i> 发表评论
                        </button>
                    </form>
                    {% else %}
                    <div class="text-center py-2">
                        <p class="mb-0">
                            请<a href="{% url 'account_login' %}" class="text-primary">登录</a>后发表评论
                        </p>
                    </div>
                    {% endif %}
                </div>
            </div>

            <div class="comment-list mt-4">
                <h4 class="mb-4">
                    <i class="fas fa-comments"></i> 评论列表
                    <small class="text-muted">（{{ comments.count }}条）</small>
                </h4>

                {% load mptt_tags %}
                <div class="row">
                    {% recursetree comments %}
                    {% with comment=node %}
                    <div class="{% if comment.reply_to %}offset-1 col-11{% else %}col-12{% endif %}"
                        id="comment_elem_{{ comment.id }}">
                        <hr>
                        <p>
                            {% if comment.user.profile.avatar %}
                            <img src="{{ comment.user.profile.avatar.url }}" class="rounded-circle mr-2"
                                style="width: 30px; height: 30px; object-fit: cover;">
                            {% else %}
                            <img src="{% static 'images/default_avatar.png' %}" class="rounded-circle mr-2"
                                style="width: 30px; height: 30px; object-fit: cover;">
                            {% endif %}
                            <strong style="color: pink">{{ comment.user }}</strong>
                            {% if comment.reply_to %}
                            <i class="far fa-arrow-alt-circle-right" style="color: cornflowerblue;"></i>
                            <strong style="color: pink">{{ comment.reply_to }}</strong>
                            {% endif %}
                        </p>
                        <div>{{ comment.body|safe }}</div>
                        <div>
                            <span style="color: gray">{{ comment.created|date:"Y-m-d H:i" }}</span>
                            {% if user == comment.user or user.is_superuser %}
                            <form class="d-inline delete-comment-form"
                                action="{% url 'comment:delete_comment' comment.id %}" method="post"
                                data-comment-id="{{ comment.id }}">
                                {% csrf_token %}
                                <button type="submit" class="btn btn-link text-danger p-0">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </form>
                            {% endif %}
                            {% if user.is_authenticated %}
                            <button type="button" class="btn btn-light btn-sm text-muted"
                                onclick="load_modal({{ article.id }}, {{ comment.id }})">
                                回复
                            </button>
                            {% else %}
                            <a class="btn btn-light btn-sm text-muted" href="{% url 'userprofile:login' %}">回复</a>
                            {% endif %}
                        </div>

                        <div class="modal fade" id="comment_{{ comment.id }}" tabindex="-1" role="dialog"
                            aria-labelledby="CommentModalCenter" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
                                <div class="modal-content" style="height: 480px">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="exampleModalCenterTitle">回复 {{ comment.user }}：</h5>
                                    </div>
                                    <div class="modal-body" id="modal_body_{{ comment.id }}"></div>
                                </div>
                            </div>
                        </div>

                        {% if not comment.is_leaf_node %}
                        <div class="children">{{ children }}</div>
                        {% endif %}
                    </div>
                    {% endwith %}
                    {% endrecursetree %}
                </div>
            </div>
        </div>

        <div class="col-3 mt-4" id="sidebar">
            <div class="sidebar__inner">
                <h4><strong>目录</strong></h4>
                <hr>
                <div>{{ toc|safe }}</div>
            </div>
        </div>
    </div>
</div>

<style>
    /* 删除按钮样式 */
    .delete-comment {
        opacity: 0;
        transition: opacity 0.2s ease;
        font-size: 0.9rem;
    }

    .comment-item:hover .delete-comment {
        opacity: 1;
    }

    .delete-comment:hover {
        color: #dc3545 !important;
        text-decoration: none;
    }

    /* 评论框加载状态 */
    .comment-form-loading {
        min-height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f8f9fa;
        border-radius: 4px;
    }

    /* 隐藏原始评论框，直到 CKEditor 完全加载 */
    .comment-form-hidden {
        display: none;
    }

    /* 添加评论内容区域的样式 */
    .comment-content {
        /* 设置最大高度，超出部分显示滚动条 */
        max-height: 500px;
        overflow-y: auto;
        /* 添加一些内边距 */
        padding: 10px 0;
    }

    /* 限制评论中图片的最大尺寸 */
    .comment-content img {
        max-width: 100%;
        height: auto;
        /* 可选：添加一些外边距 */
        margin: 10px 0;
    }

    /* 美化滚动条（可选） */
    .comment-content::-webkit-scrollbar {
        width: 2px;
    }

    .comment-content::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    .comment-content::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 3px;
    }

    .comment-content::-webkit-scrollbar-thumb:hover {
        background: #555;
    }

    /* 评论内容区域的样式 */
    .comment-content {
        padding: 10px 0;
    }

    /* 评论中图片的样式 */
    .comment-content img {
        max-width: 100%;
        height: auto;
        margin: 10px 0;
        cursor: pointer;
        /* 鼠标变为手型 */
        transition: opacity 0.3s;
        /* 添加悬停效果 */
    }

    .comment-content img:hover {
        opacity: 0.8;
    }

    /* 添加图片放大提示 */
    .comment-content img::after {
        content: '🔍';
        position: absolute;
        right: 10px;
        top: 10px;
    }

    /* 自定义模态框样式 */
    .modal-dialog {
        max-width: 90%;
        /* 更大的模态框 */
    }

    /* 模态框中的图片最大高度 */
    #modalImage {
        max-height: 80vh;
        /* 视窗高度的80% */
    }

    /* 可选：添加图片加载动画 */
    #modalImage {
        opacity: 0;
        transition: opacity 0.3s;
    }

    #modalImage.loaded {
        opacity: 1;
    }

    .sidebar {
        will-change: min-height;
    }

    .sidebar__inner {
        transform: translate(0, 0);
        transform: translate3d(0, 0, 0);
        will-change: position, transform;
    }
</style>


<!-- 粘性侧边栏 -->
<script src="{% static 'sticky_sidebar/jquery.sticky-sidebar.min.js' %}"></script>
<script type="text/javascript">
    $('#sidebar').stickySidebar({
        topSpacing: 20,
        bottomSpacing: 20,
    });
</script>



{% endblock content %}

{% block script %}
<script src="{% static 'csrf.js' %}"></script>
<script>
    function confirm_safe_delete() {
        layer.open({
            title: "确认删除",
            content: "确认删除这篇文章吗？",
            yes: function (index, layero) {
                $('form#safe_delete button').click();
                layer.close(index);
            }
        });
    }
    //打开回复模态框
    function load_modal(article_id, comment_id) {
        let modal_body = '#modal_body_' + comment_id;
        let modal_id = '#comment_' + comment_id;

        if ($(modal_body).children().length === 0) {
            $.ajax({
                url: '/comment/post-comment/' + article_id + '/' + comment_id,
                type: 'GET',
                success: function (data) {
                    $(modal_body).html(data); // 将返回的 HTML 插入到模态框中

                },
                error: function (xhr, status, error) {
                    console.error("AJAX Error: ", status, error);
                    $(modal_body).html('<p>加载评论表单失败，请重试。</p>');
                }
            });

        }

        $(modal_id).modal('show');
    }
    // 处理二级回复
    function post_reply_and_show_it(new_comment_id) {
        let next_url = "{% url 'article:article_detail' article.id %}";
        // 去除 url 尾部 '/' 符号
        next_url = next_url.charAt(next_url.length - 1) == '/' ? next_url.slice(0, -1) : next_url;
        // 刷新并定位到锚点
        window.location.replace(next_url + "#comment_elem_" + new_comment_id);
    };

    
    window.onload = function () {
        console.log('Window loaded'); // 调试用
        // 直接执行延时函数
        setTimeout(function () {
            console.log('Timeout triggered'); // 调试用
            var loadingElement = document.getElementById('comment-loading');
            var formElement = document.getElementById('comment-form');

            if (loadingElement && formElement) {
                loadingElement.style.display = 'none';
                formElement.classList.remove('comment-form-hidden');
                console.log('Elements updated'); // 调试用
            } else {
                console.log('Elements not found'); // 调试用
            }
        }, 300);
   
       // 如果URL中包含锚点，平滑滚动到目标位置
       // 锚点，定位到评论信息
       if (window.location.hash) {
        const targetElement = document.querySelector(window.location.hash);
        if (targetElement) {
            targetElement.scrollIntoView({ behavior: 'smooth' });
            // 添加高亮效果
            targetElement.style.backgroundColor = '#fff3cd';
            setTimeout(() => {
                targetElement.style.backgroundColor = '';
                targetElement.style.transition = 'background-color 0.5s ease';
            }, 2000);
        }
    }
    }




</script>

<!-- 点赞 -->
<script>
    // 点赞功能主函数
    function validate_is_like(url, id, likes) {
        // 取出 LocalStorage 中的数据
        let storage = window.localStorage;
        const storage_str_data = storage.getItem("my_blog_data");
        let storage_json_data = JSON.parse(storage_str_data);
        // 若数据不存在，则创建空字典
        if (!storage_json_data) {
            storage_json_data = {}
        };
        // 检查当前文章是否已点赞。是则 status = true
        const status = check_status(storage_json_data, id);
        if (status) {
            layer.msg('已经点过赞了哟~');
            // 点过赞则立即退出函数
            return;
        } else {
            // 用 Jquery 找到点赞数量，并 +1
            $('span#likes_number').text(likes + 1).css('color', '#dc3545');
        }
        // 用 ajax 向后端发送 post 请求
        $.post(
            url,
            // post 只是为了做 csrf 校验，因此数据为空
            {},
            function(result) {
                if (result === 'success') {
                    // 尝试修改点赞数据
                    try {
                        storage_json_data[id] = true;
                    } catch (e) {
                        window.localStorage.clear();
                    };
                    // 将字典转换为字符串，以便存储到 LocalStorage
                    const d = JSON.stringify(storage_json_data);
                    // 尝试存储点赞数据到 LocalStorage
                    try {
                        storage.setItem("my_blog_data", d);
                    } catch (e) {
                        // code 22 错误表示 LocalStorage 空间满了
                        if (e.code === 22) {
                            window.localStorage.clear();
                            storage.setItem("my_blog_data", d);
                        }
                    };
                } else {
                    layer.msg("与服务器通信失败..过一会儿再试试呗~");
                }

            }
        );
    };

    // 辅助点赞主函数，验证点赞状态
    function check_status(data, id) {
        // 尝试查询点赞状态
        try {
            if (id in data && data[id]) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            window.localStorage.clear();
            return false;
        };
    };
</script>
{% endblock script %}